package blue.web.dao.service;

import blue.tools.constants.BlueContants;
import blue.commons.enums.GradeEnum;
import blue.commons.enums.StatusEnum;
import blue.commons.models.KeyValue;
import blue.dao.base.BaseMapper;
import blue.erp.dao.BlueCourseMapper;
import blue.erp.model.BlueCourse;
import blue.erp.model.BlueCourseExample;
import blue.tools.commons.BlueStringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class BlueCourseService extends BaseService{

    @Autowired
    private BlueCourseMapper blueCourseMapper;

    private final String  UNIQE_CONSELIST_PREFIX="UNIQE_CONSELIST_PREFIX";
    private final String  UNIQE_GRADELIST_PREFIX="UNIQE_GRADELIST_PREFIX";

    public int deleteBatch(String ids,Long schoolId) {

        List idList= BlueStringUtils.convertString2Num(ids,",");
        BlueCourseExample example=new BlueCourseExample();
        example.createCriteria().andIdIn(idList).andSchoolidEqualTo(schoolId);
        clearCache(schoolId);
        return blueCourseMapper.deleteByExample(example);
    }


    public int save(BlueCourse record) {

        if(record==null || StringUtils.isBlank(record.getName())){
            return 0;
        }

        BlueCourseExample example=new BlueCourseExample();
        BlueCourseExample.Criteria criteria=example.createCriteria().andNameEqualTo(record.getName()).andSchoolidEqualTo(record.getSchoolid());

        if(StringUtils.isNotBlank(record.getType())){
            criteria.andTypeEqualTo(record.getType());
        }

        clearCache(record.getSchoolid());

        return this.baseSave(record,example);
    }

    public List<BlueCourse> selectBySchoolIdCache(Long schoolId,boolean directFormDb){

        Object cacheObject=redisService.getValue(BlueContants.prefix_courseSchool + schoolId.toString());

        if(!directFormDb && cacheObject!=null){

            return JSONArray.parseArray(cacheObject.toString(),BlueCourse.class);
        }else {
            BlueCourse blueCourse=new BlueCourse();
            blueCourse.setSchoolid(schoolId);
            List<BlueCourse> blueCourseList= select(blueCourse,false);
            if(CollectionUtils.isNotEmpty(blueCourseList)){
                redisService.setValue(BlueContants.prefix_courseSchool + schoolId.toString(),JSONArray.toJSONString(blueCourseList));
            }
            return blueCourseList;
        }
    }

    public BlueCourse selectedByName(String name,String type,Long schoolId,boolean directFormDb){

        if(StringUtils.isBlank(name) || schoolId==null){
            return null;
        }

        Object gradeCache=redisService.getValue(BlueContants.prefix_courseName +schoolId+ name+type);
        if(!directFormDb && gradeCache!=null){
            return JSONObject.parseObject(gradeCache.toString(),BlueCourse.class);
        }else {

            BlueCourseExample example=new BlueCourseExample();
            BlueCourseExample.Criteria criteria=example.createCriteria().andSchoolidEqualTo(schoolId).andNameEqualTo(name);

            if(StringUtils.isNotBlank(type)){
                criteria.andTypeEqualTo(type);
            }

            List<BlueCourse> blueCourseList=this.select(example);
            if(CollectionUtils.isEmpty(blueCourseList)){
                return null;
            }

            if(blueCourseList.size()==1){
                redisService.setValue(BlueContants.prefix_courseName +schoolId+ name+type,JSONObject.toJSONString(blueCourseList.get(0)));
            }


            return blueCourseList.get(0);
        }
    }


    public List<BlueCourse> select(BlueCourse record,boolean directFormDb){

        if (record == null) {
            return null;
        }
        BlueCourseExample example = new BlueCourseExample();
        BlueCourseExample.Criteria criteria = example.createCriteria().andSchoolidEqualTo(record.getSchoolid());

        if (record.getId() != null) {
            criteria.andIdEqualTo(record.getId());
        }

        if (StringUtils.isNotBlank(record.getName())) {
            criteria.andNameLike("%"+record.getName()+"%");
        }

        if (StringUtils.isNotBlank(record.getType())) {
            criteria.andTypeEqualTo(record.getType());
        }

        List<BlueCourse> blueCourseList = this.select(example);
        if (CollectionUtils.isEmpty(blueCourseList)) {
            return null;
        }

        return blueCourseList;
    }


    public BlueCourse selectByPrimaryKey(Long id,Long schoolId,boolean flush){

       Object cacheObject=this.baseSelectByPrimaryKey(id,BlueContants.prefix_courseId,schoolId,flush);

       if(cacheObject!=null){
           return JSONObject.parseObject(cacheObject.toString(),BlueCourse.class);
       }

       return null;
    }


    public List<BlueCourse> selectByIds(String ids,Long schoolId){

        if(StringUtils.isBlank(ids) || schoolId==null){
            return null;
        }
        Object cache = redisService.getValue(BlueContants.prefix_courseIdList+ schoolId + ids);
        if (cache != null) {
            return JSONArray.parseArray(cache.toString(),BlueCourse.class);
        } else {
            String[] courseids=ids.split(",");
            List courseInfos=new LinkedList();
            for(String course:courseids){
                BlueCourse blueCourse=selectByPrimaryKey(Long.decode(course),schoolId,false);
                if(blueCourse!=null){
                    HashMap map=new HashMap();
                    map.put("id",blueCourse.getId());
                    map.put("name",blueCourse.getName());
                    courseInfos.add(map);
                }
            }
            if(CollectionUtils.isNotEmpty(courseInfos)){
                redisService.setValue(BlueContants.prefix_courseIdList+ schoolId + ids,JSONArray.toJSONString(courseInfos));
            }
            return courseInfos;
        }

    }

    public List initCourse(int type,Long schoolId){

        String[] courses={};
        GradeEnum gradeEnum=GradeEnum.getGradeByKey(type);
        if(GradeEnum.Junior.getKey()==type){
            courses=BlueContants.junior_default_course;
        }
        if(GradeEnum.Senior.getKey()==type){
            courses=BlueContants.senior_default_course;
        }

        if(courses.length>0){
            for(KeyValue gradeDetail:GradeEnum.getGradeDetailsByKey(type)){
                for(String course:courses){
                    BlueCourse blueCourse=new BlueCourse();
                    blueCourse.setName(course);
                    blueCourse.setSchoolid(schoolId);
                    blueCourse.setType(gradeEnum.getValue());
//                    blueCourse.setGradeid(((Integer) gradeDetail.getKey()).longValue());
//                    blueCourse.setGradename((String) gradeDetail.getValue());
                    blueCourse.setStatus((byte) StatusEnum.Normal.getValue());
                    this.save(blueCourse);
                }
            }
        }

        return this.selectBySchoolIdCache(schoolId,true);

    }

    //获取学校的固定信息，比如学校的所有学科，学校的所有年级类型等
    public HashMap getConstantOfSchool(Long schoolId){
        HashMap result=new HashMap();
        List<BlueCourse> blueCourseList=this.selectBySchoolIdCache(schoolId,true);
        if(CollectionUtils.isEmpty(blueCourseList)){
            return result;
        }
        List courseList=new LinkedList();
        List gradeList=new LinkedList();
        HashMap courseMap=new HashMap();
        HashMap gradeMap=new HashMap();
        for(BlueCourse blueCourse:blueCourseList){
            if(courseMap.get(blueCourse.getName())==null){
                courseList.add(new KeyValue(blueCourse.getId(),blueCourse.getName()));
                courseMap.put(blueCourse.getName(),blueCourse.getName());
            }
//            if(gradeMap.get(blueCourse.getGradename())==null){
//                gradeList.add(new KeyValue(blueCourse.getGradeid(),blueCourse.getGradename()));
//                gradeMap.put(blueCourse.getGradename(),blueCourse.getGradename());
//            }

        }
        
        if(CollectionUtils.isNotEmpty(courseList)){
            Collections.sort(courseList);
            redisService.setValue(String.format("%s_%s",UNIQE_CONSELIST_PREFIX,schoolId),JSONArray.toJSONString(courseList));
            result.put(String.format("%s_%s",UNIQE_CONSELIST_PREFIX,schoolId),courseList);
        }

        if(CollectionUtils.isNotEmpty(gradeList)){
            Collections.sort(gradeList);
            redisService.setValue(String.format("%s_%s",UNIQE_GRADELIST_PREFIX,schoolId),JSONArray.toJSONString(gradeList));
            result.put(String.format("%s_%s",UNIQE_GRADELIST_PREFIX,schoolId),gradeList);
        }

        return result;
    }


    public List getUniqeList(Long schoolId,String prefix){

        Object setResult=redisService.getValue(String.format("%s_%s",prefix,schoolId));
        if(setResult==null){
            if(getConstantOfSchool(schoolId).get(String.format("%s_%s",prefix,schoolId))==null){
                return null;
            }
            return new LinkedList((Collection) getConstantOfSchool(schoolId).get(String.format("%s_%s",prefix,schoolId)));
        }
        return JSONArray.parseArray(setResult.toString(),KeyValue.class);
    }

    public List getUniqeCourseList(Long schoolId){

        List<BlueCourse> blueCourseList=this.selectBySchoolIdCache(schoolId,false);

        Set courseNameSet=new TreeSet();
        if(CollectionUtils.isNotEmpty(blueCourseList)){
            for(BlueCourse blueCourse:blueCourseList){
                if(StringUtils.isNotBlank(blueCourse.getName())){
                    courseNameSet.add(blueCourse.getName());
                }
            }
        }

        return new LinkedList(courseNameSet);
    }

    public List getUniqueGradeList(Long schoolId){
        return getUniqeList(schoolId,UNIQE_GRADELIST_PREFIX);
    }

    @Override
    public BaseMapper getBaseMapper() {
        return this.blueCourseMapper;
    }

    @Override
    public void clearCache(Long schoolId,Object... extend) {
        redisService.vagueDelete(BlueContants.prefix_courseSchool + schoolId);
        redisService.vagueDelete(BlueContants.prefix_courseName +schoolId);
        redisService.vagueDelete(BlueContants.prefix_courseId+schoolId);
        redisService.vagueDelete(BlueContants.prefix_courseIdList+ schoolId);
        redisService.vagueDelete(String.format("%s_%s",UNIQE_GRADELIST_PREFIX,schoolId));
        redisService.vagueDelete(String.format("%s_%s",UNIQE_CONSELIST_PREFIX,schoolId));
    }
}
